package com.cavy.platform.server.repository.impl;

import com.cavy.platform.server.CavyConfig;
import com.cavy.platform.server.domain.job.ContainerLogSubscribeKey;
import com.cavy.platform.server.dto.JobLogDto;
import com.cavy.platform.server.repository.JobLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.File;

@Repository
public class JobLogRepositoryImpl implements JobLogRepository {
    public static final String DEPENDENCY = "%s-%s-%s-%s-%s-%s-StageDependency-%s.log";
    public static final String CONTAINER = "%s-%s-%s-%s-%s-%s.log";
    @Autowired
    private CavyConfig config;

    @Override
    public File load(JobLogDto dto) {
        return getFile(dto.getWorkSpace(), dto.getProject(), dto.getPipeline(), dto.getNumber(), dto.getStage(), dto.getContainerIndex(), dto.getDependencyIndex());
    }

    @Override
    public File load(ContainerLogSubscribeKey key) {
        return getFile(key.getWorkSpace(), key.getProject(), key.getPipeline(), key.getNumber(), key.getStage(), key.getContainerIndex(), key.getDependencyIndex());
    }

    private File getFile(String workSpace, String project, String pipeline, String number, String stage, int containerIndex, int dependencyIndex) {
        File parentDir = getParentDir();
        String fileName = getFileName(workSpace, project, pipeline, number
                , stage, containerIndex, dependencyIndex);
        File file = new File(parentDir, fileName);
        if (!file.exists()) {
            return null;
        }
        return file;
    }

    private String getFileName(String workSpace, String project, String pipeline, String number, String stage,
                               int containerIndex, int dependencyIndex) {
        if (dependencyIndex >= 0) {
            return String.format(DEPENDENCY, workSpace, project, pipeline, number, stage, containerIndex, dependencyIndex);
        } else {
            return String.format(CONTAINER, workSpace, project, pipeline, number, stage, containerIndex);
        }
    }

    private File getParentDir() {
        File dir = config.getJob().getLogDirFile();
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建文件夹:" + dir.getPath() + "失败");
            }
        }
        return dir;
    }
}
